// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import HttpModule from "./HttpModule";
import FileModule from "./FileModule";
import LogModule from "./LogModule";
import TushareModule from "./TushareModule";

const {ccclass, property} = cc._decorator;

@ccclass
export default class SeptkapaModule {
    
    public static _instance: SeptkapaModule = null;
  
    public rootPath: string = '';

    public tushareToken: string = '';

    private _configPath: string = '';

    private configMap: Object = {};

    static getInstance(): SeptkapaModule {
        if (SeptkapaModule._instance == null) {
            SeptkapaModule._instance = new SeptkapaModule();
        }
        return SeptkapaModule._instance;
    }

    async initModule () {
        this._configPath = jsb.fileUtils.getWritablePath() + 'data/';
        let file = this._configPath + 'config.json';
        if (jsb.fileUtils.isDirectoryExist(this._configPath) == false) {
            jsb.fileUtils.createDirectory(this._configPath);
            let config = null;
            if (cc.sys.os === cc.sys.OS_WINDOWS) {
                config = this.initWin();
            } else {
                config = this.initMobile();
            }
            let str = JSON.stringify(config);
            str = FileModule.formatJson(str, null);
            jsb.fileUtils.writeStringToFile(str, file);
        } 
        LogModule.log('正在加载配置文件');
        var json:any = await new Promise((resolve) => {
            cc.assetManager.loadRemote(file, cc.JsonAsset, (result: Error, asset: cc.JsonAsset) => {
                if (asset && asset.json) {
                    resolve(asset.json);
                }
            });
        });
        this.rootPath = json.data_root_path;
        this.tushareToken = json.tushare_token;
        this.tushareToken = "2876ea85cb005fb5fa17c809a98174f2d5aae8b1f830110a5ead6211";
        if (json.config_map) {
            this.configMap = json.config_map;
        }
        
        LogModule.log('正在加载数据');
        await this.initConfig();
    }

    initMobile () {
        let root = jsb.fileUtils.getWritablePath();
        let config = {
            data_root_path: root + 'sept-kapa/data/',
            tushare_token: '591e6891f9287935f45fc712bcf62335a81cd6829ce76c21c0fdf7b2',
        };

        if (jsb.fileUtils.isDirectoryExist(root + 'sept-kapa/')) {
            jsb.fileUtils.createDirectory(root + 'sept-kapa/');
        }
        if (jsb.fileUtils.isDirectoryExist(root + 'sept-kapa/data/')) {
            jsb.fileUtils.createDirectory(root + 'sept-kapa/data/');
        }

        return config;
    }

    initWin () {
        let config = {
            data_root_path: 'F:/sept-kapa/data/',
            tushare_token: '591e6891f9287935f45fc712bcf62335a81cd6829ce76c21c0fdf7b2',
        };

        if (jsb.fileUtils.isDirectoryExist('F:/sept-kapa/')) {
            jsb.fileUtils.createDirectory('F:/sept-kapa/');
        }
        if (jsb.fileUtils.isDirectoryExist('F:/sept-kapa/data/')) {
            jsb.fileUtils.createDirectory('F:/sept-kapa/data/');
        }

        return config;
    }

    async initConfig () {
        HttpModule.tokenKey = this.tushareToken;
        FileModule.init();
        await TushareModule.getInstance().initModule();

        window['__errorHandler'] = function () {
            var msg = { 
                file    : arguments[0],
                file1   : arguments[1],
                error   : arguments[2],
                stack   : arguments[3],
                os      : cc.sys.os
            };
            var strMsg = JSON.stringify(msg);
            LogModule.log(strMsg);
        };
    }

    setValue (key, value) {
        this.configMap[key] = value;
        this.save();
    }

    getValue (key) {
        if (this.configMap == null) {
            return null;
        }
        return this.configMap[key];
    }
    
    save () {
        let config = {
            data_root_path: this.rootPath,
            tushare_token: this.tushareToken,
            config_map: this.configMap,
        };
        let file = this._configPath + 'config.json';
        let str = JSON.stringify(config);
        jsb.fileUtils.writeStringToFile(str, file);
    }
}
